# -*- coding : utf_8 -*-
"""
=======================================
Time : 2025/3/22 21:55
Author : 田霄汉
Email : 522989570@qq.com
File : debugtalk_util.py
Project : pytest_demo
=======================================
"""
import json
from utils.log_util import logs


class DebugtalkUtil:

    def __init__(self, obj):
        # 需要将类名DebugTalk()传参给DebugtalkUtil()
        self.obj = obj

    def debugtalk_replace_value(self, data):
        """
        测试用例yaml文件中的${function(**kwargs)}解析成debug_talk.py中的function(**kwargs)执行
        :param data: ${function(**kwargs)}
        :return: function(**kwargs)执行后的结果
        """
        try:
            if data:
                # 保存数据类型
                data_type = type(data)
                # 判断数据类型转换成str
                if isinstance(data, dict) or isinstance(data, list):
                    str_data = json.dumps(data)
                else:
                    str_data = str(data)
                for cs in range(1, str_data.count('${') + 1):
                    # 替换
                    if "${" in str_data and "}" in str_data:
                        start_index = str_data.index("${")
                        end_index = str_data.index("}", start_index)
                        old_value = str_data[start_index:end_index + 1]
                        # logs.debug('热加载函数为{old_value}')
                        # 反射：通过类的对象和方法字符串调用方法
                        func_name = old_value[2:old_value.index('(')]
                        args_value1 = old_value[old_value.index('(') + 1:old_value.index(')')].replace(" ", "")
                        # new_value = ""
                        if args_value1 != "":
                            args_value2 = args_value1.split(',')
                            new_value = getattr(self.obj, func_name)(*args_value2)
                        else:
                            new_value = getattr(self.obj, func_name)()
                        str_data = str_data.replace(old_value, str(new_value))
                        logs.info(f'{old_value}热加载成功')
                # 还原数据类型
                if isinstance(data, dict) or isinstance(data, list):
                    data = json.loads(str_data)
                else:
                    data = data_type(str_data)
            return data
        except Exception as e:
            logs.error(f'热加载报错信息为{e}')
